import React from 'react';

import Header from '../common/Header';
import CKModal from '../components/CKModal';
import Validate from '../common/Validate';
import moment from 'moment';
import AMUIReact,{
    Button,
    Input,
    Form,
    Icon,
    Selected,
    FormGroup
} from 'amazeui-react';

import Fetch from '../common/Fetch';

class MenuEdit extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            data:{},
            menu_data:[],
            page:{
                pageSize:20,
                currentPage:1,
                totalNum:43
            },
            upload_img:'',
            is_save:false,
            type:this.props.params.id ? 'edit':'add',
            init:false,
            is_top:false,
            menu_id:this.props.params.id?this.props.params.id:''
        };
    }

    componentDidMount() {
        Fetch('/admin/menu_manage/get_parent_menu',{cipher_id:0},(res)=>{
            if (res.status) {
                this.setState({
                    menu_data:res.data.data
                });
                this.getMenuData()
            } else {
                this.refs.modal.alert('提示','加载分组数据出错',()=>{
                    this.context.router.push('/menu_manage');
                    return true;
                });
            }
        },()=>{
            this.refs.modal.closeModal();
        });
    }

    getMenuData() {
        if (this.state.type === 'edit') {
            this.refs.modal.load('正在加载数据...');
            Fetch('/admin/menu_manage/get_menu',{id:this.props.params.id},(res)=>{
                if (res.status) {
                    this.setState({
                        data:res.data,
                        is_top:res.data.menu_parent=="0"
                    });
                    this.refs.modal.closeModal();
                } else {
                    this.refs.modal.alert('提示','加载菜单数据数据出错',()=>{
                        this.context.router.push('/menu_manage');
                        return true;
                    });
                }
            },()=>{
                this.refs.modal.closeModal();
            });
        }
    }

    saveMenu = ()=>{
        var data = this.checkData();
        if (data === false) return;

        if (this.state.is_save) return;
        this.setState({
            is_save:true
        });
        this.refs.modal.load('正在保存数据...');
        Fetch('/admin/menu_manage/save',{data:data},(res)=>{
            if (res.status) {
                this.refs.modal.alert('成功','保存菜单数据成功!',()=>{
                    this.context.router.push('/menu_manage');
                });
            } else {
                this.refs.modal.alert('失败','保存菜单失败!!');
                this.setState({
                    is_save:false
                });
            }
        },()=>{
            this.refs.modal.alert('失败','远程调用失败!!');
            this.setState({
                is_save:false
            });
        });
    };

    changeHandler(field){
        return (e)=>{
            var info = this.state.data;
            info[field] = e.target.value;
            this.setState({data:info});
        }
    }

    checkData() {
        var valid = {
            'menu_parent':{role:'*',errmsg:'上级菜单不能为空'},
            'menu_text':{role:'s2-40',errmsg:'菜单显示名称为2到20个字符'},
            'menu_name':{role:'s2-40',errmsg:'菜单名称为2到20个字符'},
            'menu_link':{role:'*2-100',errmsg:'菜单方法为2到40个任意字符'},
            'menu_sort':{role:'n1-10',errmsg:'菜单排序只能是数字，长度最大10位'}
        };
        var data = {};
        $.map(this.refs,(item,key)=>{
            if (/^menu/.test(key)) {
                let field = item.props.field || key;
                data[field] = item.getValue();
            }
        });
        if (this.state.type === 'edit') {
            data['menu_id'] = this.props.params.id;
        }
        if (this.state.is_top) {
            data['menu_parent'] = "0";
            data['menu_parent_text'] = "顶级菜单";
        } else {
            this.state.menu_data.forEach((item)=>{
                if (data['menu_parent'] === item.value) {
                    data['menu_parent_text'] = item.label
                }
            })
        }
        try {
            Validate.inst().checkData(data,valid);
            return data;
        } catch (e) {
            this.refs.modal.alert('错误',e);
            return false;
        }
    }

    validate() {

    }

    topHandler = (e)=>{
        this.setState({
            is_top:e.target.checked
        });
        this.refs.menu_parent.setValue('');
    };

    selectChange = (e)=>{
        if(e != '') {
            this.setState({
                is_top: false
            });
        }
    };

    render() {
        var data = this.state.data;
        return (
            <div className="content">
                <Header title={this.state.type === 'edit'?'修改菜单':'添加菜单'} back={true}/>
                <div className="content_main">
                    <div style={{marginBottom:'20px'}}>
                        <h4 className="title">菜单信息</h4>
                    </div>
                    <Form ref="from" horizontal style={{marginTop:'20px'}}>
                        <div className="am-form-group">
                            <label className="am-u-sm-2 am-form-label">
                                上级菜单
                            </label>
                            <div className="am-u-sm-4 am-u-end">
                                <Selected onChange={this.selectChange}
                                          ref="menu_parent" field="menu_parent"
                                          placeholder="请选择上级菜单"
                                          btnStyle="primary" data={this.state.menu_data}
                                          value={data.menu_parent || ''}
                                          disabled={this.state.is_top}/>
                                <Input onChange={this.topHandler} ref="top" checked={this.state.is_top} type="checkbox" name="doc-checkbox-1" label="顶级菜单" inline />
                            </div>
                        </div>
                        <Input id="menu_text" ref="menu_text" label="菜单显示名称"
                               labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.menu_text}
                               placeholder="菜单显示名称为2到20个字符"
                               onChange={this.changeHandler('menu_text')}
                        />
                        <Input id="menu_name" ref="menu_name" label="菜单名称"
                               labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.menu_name}
                               placeholder="菜单名称为2到20个字符"
                               onChange={this.changeHandler('menu_name')}
                        />
                        <Input id="menu_link" ref="menu_link" label="菜单方法"
                               labelClassName="am-u-sm-2"
                               placeholder="菜单方法为2到40个任意字符"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.menu_link}
                               onChange={this.changeHandler('menu_link')}
                        />
                        <Input id="menu_icon" ref="menu_icon" label="菜单图标"
                               labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.menu_icon}
                               onChange={this.changeHandler('menu_icon')}
                        />
                        <Input id="menu_sort" ref="menu_sort" label="排序"
                               labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.menu_sort}
                               placeholder="排序只能是数字，长度最大10位"
                               onChange={this.changeHandler('menu_sort')}
                        />
                        <Input label="添加时间" labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={moment.unix(data.created_date).format('YYYY-MM-DD HH:mm:ss')}
                               disabled
                        />
                    </Form>
                    <div className="am-form-group">
                        <div className="am-u-sm-2">
                            &nbsp;
                        </div>
                        <div className="am-u-sm-4 am-u-end">
                            <Button amStyle="primary"
                                    onClick={this.saveMenu}
                                    disabled={this.state.is_save}
                            >
                                {this.state.is_save?'保存中...':'保存'}
                            </Button>
                        </div>
                    </div>
                </div>
                <CKModal ref="modal"/>
            </div>
        );
    }
}

MenuEdit.contextTypes = {
    router: React.PropTypes.object
};

export default MenuEdit;